#ifndef __TASK_H__
#define __TASK_H__

#include <iostream>
#include <string>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <unistd.h>
#include <sys/types.h>

using task_t = std::function<void()>;

void Downlode()
{
    std::cout << "我是下载任务...,pid:" << getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务...,pid:" << getpid()<< std::endl;
}

void Sql()
{
    std::cout << "我是数据库同步任务...,pid:" << getpid() << std::endl;
}
static int number = 0;

class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        InsertTask(Downlode);
        InsertTask(Log);
        InsertTask(Sql);
    }
    void InsertTask(task_t t) // 插入
    {
        tasks[number++] = t;
    }
    int SelectTask()   //选择任务
    {
        return rand()%number;   //随机选择一个任务
    }
    void Excute(int number) // 执行
    {
        if (tasks.find(number) == tasks.end())
            return;
        tasks[number]();
    }

    ~TaskManger()
    {
    }

private:
    std::unordered_map<int, task_t> tasks;
};

TaskManger tm;

void Worker()
{
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd)); // 读取任务编号
        if (n == sizeof(cmd))
        {
            // 读取成功
            tm.Excute(cmd);
        }
        else if (n == 0)
        {
            //取到到文件末尾
            std::cout << "pid:" << getpid() << " quit..." << std::endl;
            break;
        }
        else
        {
        }
    }
}
#endif